﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;

namespace NJL.Web
{
    public class BasePageVisitor : System.Web.UI.Page
    {
        /// <summary>
        /// 网站编号
        /// </summary>
        public string WEBSITE_CODE
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["WebSiteCode"]; }
        }

        /// <summary>
        /// 网站名称
        /// </summary>
        public string WEBSITE_NAME
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["WebSiteName"]; }
        }

        /// <summary>
        /// 网站域名
        /// </summary>
        public string WEBSITE_DOMAIN
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["WebSiteDomain"]; }
        }

        /// <summary>
        /// 网站图片域名
        /// </summary>
        public string WEBSITE_IMAGE_DOMAIN
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["WebSiteImageDomain"]; }
        }

        /// <summary>
        /// 网站用户登录域名
        /// </summary>
        public string WEBSITE_USRE_DOMAIN
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["WebSiteUserDomain"]; }
        }

        /// <summary>
        /// 网站默认城市编号
        /// </summary>
        public string WEBSITE_DEFAULT_CITY_CODE
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["DefaultCityCode"]; }
        }

        /// <summary>
        /// 网站默认城市名称
        /// </summary>
        public string WEBSITE_DEFAULT_CITY_NAME
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["DefaultCityName"]; }
        }

        /// <summary>
        /// 当前网站城市编号
        /// </summary>
        public string WEBSITE_FOCUS_CITY_CODE
        {
            get
            {
                if (Request.QueryString["cc"] != null)
                {
                    Model.NJL_CS_AREA model = new BLL.NJL_CS_AREA().GetModel(WEBSITE_CODE, Request.QueryString["cc"].ToLower());
                    if (null != model)
                    {
                        return model.AREA_CODE;
                    }
                    else
                    {
                        return "";
                    }
                }
                else
                {
                    return "";
                }
            }
        }

        /// <summary>
        /// 当前网站城市名称
        /// </summary>
        public string WEBSITE_FOCUS_CITY_NAME
        {
            get
            {
                if (WEBSITE_FOCUS_CITY_CODE != "")
                {
                    return new BLL.NJL_CS_AREA().GetModel(WEBSITE_FOCUS_CITY_CODE).AREA_NAME;
                }
                else
                {
                    if (WEBSITE_CODE != "110000" && WEBSITE_CODE != "120000" && WEBSITE_CODE != "310000" && WEBSITE_CODE != "500000")
                    {
                        return "全省";
                    }
                    else
                    {
                        return "全市";
                    }
                }
            }
        }

        /// <summary>
        /// 当前网站城市名称拼音
        /// </summary>
        public string WEBSITE_FOCUS_CITY_NAME_PINYIN
        {
            get
            {
                if (WEBSITE_FOCUS_CITY_CODE != "")
                {
                    return new BLL.NJL_CS_AREA().GetModel(WEBSITE_FOCUS_CITY_CODE).AREA_NAME_PINYIN;
                }
                else
                {
                    return "";
                }
            }
        }

        /// <summary>
        /// 获取当前网站的基本信息
        /// </summary>
        public Model.NJL_SYS_BASE WEBSITE_SYS_BASE
        {
            get { return new BLL.NJL_SYS_BASE().GetModelByCache(WEBSITE_CODE); }
        }

        public BasePageVisitor()
        {
            this.Load += new EventHandler(CheckDomain);
        }

        //protected override void OnInit(EventArgs e)
        //{
        //    if (Session["userid"] == null || Session["username"] == null || Session["usertype"]==null)
        //    {
        //        Response.Redirect("~/Login.aspx");
        //    }
        //}

        /// <summary>
        /// 用户编号
        /// </summary>
        public string UserId
        {
            get
            {
                if (Session["userid"] != null)
                {
                    return Session["userid"].ToString();
                }
                else
                {
                    return "";
                }
            }

        }
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get
            {
                if (Session["username"] != null)
                {
                    return Session["username"].ToString();
                }
                else
                {
                    return "";
                }
            }

        }
        /// <summary>
        /// 网站编号
        /// </summary>
        public string WebSiteCode
        {
            get
            {
                return WEBSITE_CODE;
            }
        }

        /// <summary>
        /// 用户类型
        /// </summary>
        public string UserType
        {
            get
            {
                if (Session["usertype"] != null)
                {
                    return Session["usertype"].ToString();
                }
                else
                {
                    return "";
                }
            }
        }

        /// <summary>
        /// 根据PersonID获取UserID
        /// </summary>
        /// <param name="PersonID"></param>
        /// <returns></returns>
        public string GetUserIDByPersonID(string PersonID)
        {
            Model.NJL_PERSON model = new BLL.NJL_PERSON().GetModel(PersonID);
            if (model != null)
            {
                return model.NJL_USER_ID;
            }
            else
            {
                return "";
            }
        }


        #region 后台图片上传、读取、删除公共处理方法

        public string SaveUploadFile(HttpFileCollection ContractFile)
        {
            string strImageID = "";
            string strFileName = FileManageGetFileName();
            string strFileType = FileManageGetFileType(ContractFile);
            string strFileSavePath = FileManageGetFileUrlPath(WebSiteCode, UserType);
            string strFileLocalPath = HttpContext.Current.Server.MapPath(strFileSavePath);
            //
            if (Royalsoft.Common.FileManage.SaveFile(ContractFile, strFileLocalPath, strFileName, strFileType))
            {
                BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();
                Model.NJL_IMAGE model = new Model.NJL_IMAGE();

                model.IMAGE_NAME = strFileName;
                model.IMAGE_TYPE = strFileType;
                model.IMAGE_URL_PATH = strFileSavePath;
                model.IMAGE_LOCAL_PATH = strFileLocalPath;
                model.IMAGE_FROM_TYPE = Convert.ToInt32(UserType);
                model.ID = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(111, 999).ToString();
                model.CREATE_USER_ID = UserId;
                model.CREATE_USER_NAME = UserName;
                model.CREATE_DATE_TIME = System.DateTime.Now;

                bll.Add(model);

                strImageID = model.ID;
            }

            return strImageID;
            //
        }
        /// <summary>
        /// 获得文件存储路径
        /// </summary>
        /// <param name="WebsiteCode">网站编号</param>
        /// <param name="UserType">用户类型：1：User，2：Admin</param>
        /// <returns></returns>
        public string FileManageGetFileUrlPath(string WebsiteCode, string UserType)
        {
            string strFileSavePath = "";
            DateTime dtime = DateTime.Now;

            strFileSavePath = System.Configuration.ConfigurationManager.AppSettings["UploadFileSavePath"] + "/" + WebsiteCode + "/" + UserType + "/" + dtime.ToString("yyyy") + "/" + dtime.ToString("MM") + "/" + dtime.ToString("dd") + "/";

            return strFileSavePath;
        }

        /// <summary>
        /// 获得文件物理路径
        /// </summary>
        /// <param name="FileUrlPath">文件URL路径</param>
        /// <returns></returns>
        public string FileManageGetFileLocalPath(string FileUrlPath)
        {
            string strFileSavePath = "";
            DateTime dtime = DateTime.Now;

            strFileSavePath = System.Configuration.ConfigurationManager.AppSettings["UploadFileSavePath"] + "/" + WebSiteCode + "/" + dtime.ToString("yyyy") + "/" + dtime.ToString("MM") + "/" + dtime.ToString("dd") + "/";

            return strFileSavePath;
        }

        /// <summary>
        /// 获得新文件名称
        /// </summary>
        /// <returns></returns>
        public string FileManageGetFileName()
        {
            return System.Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 获得文件的类型
        /// </summary>
        /// <param name="ContractFile"></param>
        /// <returns></returns>
        public string FileManageGetFileType(HttpFileCollection ContractFile)
        {
            string strFileType = "";
            if (ContractFile[0].ContentLength > 0)
            {
                strFileType = ContractFile[0].FileName.Substring(ContractFile[0].FileName.LastIndexOf("."));

                //strFileType = ContractFile[0].ContentType;
            }

            return strFileType;
        }

        /// <summary>
        /// 通过图片编号获取图片URL路径
        /// </summary>
        /// <param name="ImageCode"></param>
        /// <returns></returns>
        public static string GetImageUrl(string ImageCode)
        {
            BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();

            Model.NJL_IMAGE model = bll.GetModel(ImageCode);

            if (model != null)
            {
                return System.Configuration.ConfigurationManager.AppSettings["WebSiteImageDomain"] + model.IMAGE_URL_PATH + model.IMAGE_NAME + model.IMAGE_TYPE;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 通过图片编号获取图片URL路径
        /// </summary>
        /// <param name="ImageCode"></param>
        /// <returns></returns>
        public static string GetImageUrl(string ImageCode, string SizeType)
        {
            BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();

            Model.NJL_IMAGE model = bll.GetModel(ImageCode);

            if (model != null)
            {
                return System.Configuration.ConfigurationManager.AppSettings["WebSiteImageDomain"] + "/?st=" + SizeType.Trim() + "&id=" + model.ID;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 通过图片编号删除图片
        /// </summary>
        /// <param name="ImageCode"></param>
        /// <returns></returns>
        public bool DeleteImageByCode(string ImageCode)
        {
            BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();

            Model.NJL_IMAGE model = bll.GetModel(ImageCode);
            if (model != null)
            {
                if (Royalsoft.Common.FileManage.DeletePicture(model.IMAGE_URL_PATH + model.IMAGE_NAME + model.IMAGE_TYPE))
                {
                    return bll.Delete(ImageCode);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region SQL注入过滤
        /// <summary>
        ///SQL注入过滤
        /// </summary>
        /// <param name="InText">要过滤的字符串</param>
        /// <returns>如果参数存在不安全字符，则返回true</returns>
        public static bool SqlFilter(string InText)
        {
            string word = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join";
            if (InText == null)
                return false;
            foreach (string i in word.Split('|'))
            {
                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 页面加载配置SEO
        /// <summary>
        /// 加载该页面的SEO信息
        /// </summary>
        /// <param name="SEO_NAME">SEO栏目名称，后台设置</param>
        public void LoadPageSeoInformation(string SEO_NAME)
        {
            string strSeoTitle = "";
            string strSeoKeywords = "";
            string strSeoDescription = "";

            BLL.NJL_SEO_CONFIG bllSeoConfig = new BLL.NJL_SEO_CONFIG();
            string strWhere = "";
            if (WEBSITE_FOCUS_CITY_CODE != "")
            {
                strWhere = " NJL_SEO_CONFIG.NJL_SYS_BASE_ID='" + WEBSITE_CODE + "' AND NJL_SEO_CONFIG.SEO_NAME='" + SEO_NAME + "' AND NJL_SEO_CONFIG.AREA_CODE='" + WEBSITE_FOCUS_CITY_CODE + "' ";
            }
            else
            {
                strWhere = " NJL_SEO_CONFIG.NJL_SYS_BASE_ID='" + WEBSITE_CODE + "' AND NJL_SEO_CONFIG.SEO_NAME='" + SEO_NAME + "' AND NJL_SEO_CONFIG.AREA_CODE='0' ";
            }
            IList<Model.NJL_SEO_CONFIG> listSeoConfig = bllSeoConfig.GetModelList(strWhere);

            if (listSeoConfig.Count > 0)
            {
                strSeoTitle = listSeoConfig[0].SEO_TITLE;
                strSeoKeywords = listSeoConfig[0].SEO_KEYWORDS;
                strSeoDescription = listSeoConfig[0].SEO_DESCRIPTION;
            }

            Page.Title = strSeoTitle;

            HtmlMeta myMeta = new HtmlMeta();
            myMeta.Name = "Keywords";
            myMeta.Content = strSeoKeywords;
            this.Header.Controls.Add(myMeta);

            HtmlMeta myMeta1 = new HtmlMeta();
            myMeta1.Name = "Description";
            myMeta1.Content = strSeoDescription;
            this.Header.Controls.Add(myMeta1);
        }
        #endregion

        #region 积分规则
        /// <summary>
        /// 积分处理
        /// </summary>
        /// <param name="TypeCode">用户ID</param>
        /// <param name="TypeCode">积分编号</param>
        public bool HandleIntegral(string User_ID, string TypeCode, out string message)
        {
            message = "";
            BLL.NJL_CS_INTEGRAL_TYPE bllCS = new BLL.NJL_CS_INTEGRAL_TYPE();
            Model.NJL_CS_INTEGRAL_TYPE modelCS = bllCS.GetModelByCache(TypeCode);
            BLL.NJL_USER bllUser = new BLL.NJL_USER();
            Model.NJL_USER modelUser = bllUser.GetModel(User_ID);
            BLL.NJL_REG_INTEGRAL bllReg = new BLL.NJL_REG_INTEGRAL();

            if (modelCS != null && modelUser != null)
            {
                Model.NJL_REG_INTEGRAL modelReg = new Model.NJL_REG_INTEGRAL();
                modelReg.ID = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(100, 999).ToString();
                modelReg.NJL_SYS_BASE_ID = WEBSITE_CODE;
                modelReg.NJL_USER_ID = modelUser.ID;
                modelReg.TYPE_CODE = modelCS.TYPE_CODE;
                modelReg.INTEGRAL = modelCS.INTEGRAL;
                modelReg.CREATE_DATE_TIME = System.DateTime.Now;

                bllReg.Add(modelReg);
                message = modelCS.TYPE_NAME;
                modelUser.INTEGRAL = modelUser.INTEGRAL + modelCS.INTEGRAL;
                return bllUser.Update(modelUser);
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region url重写form
     
        protected override void Render(HtmlTextWriter writer)
        {  
            if (writer is System.Web.UI.Html32TextWriter)
            {
                writer = new FormFixerHtml32TextWriter(writer.InnerWriter);
            }
            else
            {
                writer = new FormFixerHtmlTextWriter(writer.InnerWriter);
            }
            base.Render(writer);       

        }
        internal class FormFixerHtml32TextWriter : System.Web.UI.Html32TextWriter
        {
            private string _url; // 假的URL
            internal FormFixerHtml32TextWriter(TextWriter writer)
                : base(writer)
            {
                _url = HttpContext.Current.Request.RawUrl;
            }
            public override void WriteAttribute(string name, string value, bool encode)
            {
                if (_url != null && string.Compare(name, "action", true) == 0)
                {
                    value = _url;
                }
                base.WriteAttribute(name, value, encode);
            }
        }
        internal class FormFixerHtmlTextWriter : System.Web.UI.HtmlTextWriter
        {
            private string _url;
            internal FormFixerHtmlTextWriter(TextWriter writer)
                : base(writer)
            {
                _url = HttpContext.Current.Request.RawUrl;
            }
            public override void WriteAttribute(string name, string value, bool encode)
            {
                if (_url != null && string.Compare(name, "action", true) == 0)
                {
                    value = _url;
                }
                base.WriteAttribute(name, value, encode);
            }

        }
        #endregion

        #region 根据城市编号获取城市拼音
        public string GetAreaNamePinYin(string AreaCode)
        {
            Model.NJL_CS_AREA model = new BLL.NJL_CS_AREA().GetModelByCache(AreaCode);

            if (null != model)
            {
                return model.AREA_NAME_PINYIN;
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 301处理
        //301处理
        private void CheckDomain(Object sender, EventArgs e)
        {
            if (Session["url"] != null && Session["url"].ToString()!= "")
            {
                string strUrlTemp = "http://" + WEBSITE_DOMAIN + Session["url"].ToString();
                Session.Remove("url");
                Response.Redirect(strUrlTemp, true);
            }

            string strRawUrl = Request.RawUrl;

            string strDomain = Request.Url.Host;
            if (strDomain == "localhost")
                return;
            if (strDomain != WEBSITE_DOMAIN)
            {
                string strURL = Request.Url.ToString();
                //strURL = strURL.Substring(7);
                //strURL = strURL.Substring(strURL.IndexOf("/"));
                strURL = "http://" + WEBSITE_DOMAIN + strRawUrl;
                //strURL = "http://" + WEBSITE_DOMAIN;

                Response.Redirect(strURL, true);
                //Response.Redirect(Request.Url.ToString().Replace("51maihua.cn", "www.51maihua.cn"), true);
            }
        }
        #endregion

        #region 订票付款方式
        public string GetBookPayType(string TypeCode)
        {
            Model.NJL_CS_BOOK_PAY model = new BLL.NJL_CS_BOOK_PAY().GetModelByCache(TypeCode);

            if (null != model)
            {
                return model.TYPE_NAME;
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 页面调用短信发送接口
        public string SendSMS(string Mobile, string SMSContent)
        {
            //北京公司短信接口
            string i = SmsMD(Mobile, SMSContent);
            
            //int i = Royalsoft.Common.SMS.SendSMS(System.Configuration.ConfigurationManager.AppSettings["SMSSN"], Mobile, SMSContent, "5");

            return i;
        }

        /// <summary>
        /// 北京MD短信公司短信平台
        /// </summary>
        /// <param name="Mobile"></param>
        /// <param name="SMSContent"></param>
        /// <returns></returns>
        private string SmsMD(string Mobile, string SMSContent)
        {
            string SmsMD_SN = System.Configuration.ConfigurationManager.AppSettings["SMSMDSN"];
            string SmsMD_PWD = System.Configuration.ConfigurationManager.AppSettings["SMSMDPWD"];
            string SmsMD_Password = SmsMDgetMD5(SmsMD_SN + SmsMD_PWD);
            Web.sms.WebService sms = new Web.sms.WebService();

            string strValue = sms.mt(SmsMD_SN, SmsMD_Password, Mobile, SMSContent, "", "", "");

            return strValue;
        }
        /// <summary>
        /// 获取md5码------北京MD短信公司短信平台
        /// </summary>
        /// <param name="source">待转换字符串</param>
        /// <returns>md5加密后的字符串</returns>
        private string SmsMDgetMD5(string source)
        {
            string result = "";
            try
            {
                MD5 getmd5 = new MD5CryptoServiceProvider();
                byte[] targetStr = getmd5.ComputeHash(UnicodeEncoding.UTF8.GetBytes(source));
                result = BitConverter.ToString(targetStr).Replace("-", "");
                return result;
            }
            catch (Exception)
            {
                return "0";
            }
        }

        #endregion
    }
}